use std::process::Command;
use std::error::Error;
use std::str;
use std::path::Path;
use log::error;
// type Out<T> = Result<T, &'static str>;
type OutErr<T> = Result<T, Box<dyn Error>> ;



pub fn use_pdftotext() -> bool{
    if cfg!(target_os = "windows"){
        false
    }else{
        let mut test_path = String::new();
        let _ = vec!["/usr/local/bin", "/usr/bin/", "/bin/"].iter().map(|&dir_str|{
            test_path = format!("{}{}", dir_str, "pdftotext");
            let path = Path::new(&test_path);
            path.exists()
        }).collect::<Vec<_>>();
        true
    }
    
}

pub fn get_pdf_text(path:&Path) -> OutErr<String> {
    let mut buf = String::new();
    let f_name = path.to_str().unwrap();
    let output = if cfg!(target_os = "windows") {
            Command::new("cmd")
                .arg("/C")
                .arg(format!("pdftotext  \"{}\" - ", f_name))
                .output()
                .expect("failed to execute process")
        } else {
            Command::new("sh")
                .arg("-c")
                .arg(format!("pdftotext  \"{}\" - ", f_name))
                .output()
                .expect("failed to execute process")
    };

    if output.status.success() {
        buf.push_str(str::from_utf8(&output.stdout)?);
        Ok(buf)
    }else{
        error!("{} \n {}",str::from_utf8(&output.stdout)?,str::from_utf8(&output.stderr)? );
        Err(format!("pdf parse error :{} ", f_name))?
    }
}